var utils = require("../../../utils/utils.js");
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    name: "",
    icon: "",
    disabledFlag: false,
    totalDays:0,
    monthDays:0,
    habitInfo: {},
    currentDate: null,
    currentMonth: null,
    currentYear: null,
    nowYear: new Date().getFullYear(),
    nowMonth: new Date().getMonth(),
    nowDate:new Date().getDate(),
    punchCardDateArr: [], //用于存放当月打卡日期-日
    balance:'',
    firstOpen:0,
    amount:'0.00'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      name: options.name,
      icon: options.icon
    })
    var nowYear = new Date().getFullYear()
    var nowMonth = new Date().getMonth()
    wx.nextTick(() => {
      this.getHabitInfo(nowYear, nowMonth)
    })
  },
  // 获取子组件的数据
  getObj(e) {
    this.setData({
      currentDate: e.detail.currentDate,
      currentMonth: e.detail.currentMonth,
      currentYear: e.detail.currentYear,
    })
    this.getHabitInfo(e.detail.currentYear, e.detail.currentMonth - 1)
  },
    //获取总余额
    getAll(){
        var that = this;
        utils.request('sign/signLists', {
            page:'1',
            limit:'1',
        }, function (res) {
           if(res.data.code==200){
             that.setData({
                amount:res.data.data.signTotalAmount
             })
           }else{
              utils.toast(res.data.msg)
           }
        })
    },
  // 获取当月的打卡数据
  getHabitInfo(year, month) {   
    month = parseInt(month)+1;
    var that = this;
    utils.request('sign/signLists', {
      page:'1',
      limit:'31',
      year:year,
      month:month>9?month:'0'+month
  }, function (res) {
     if(res.data.code==200){
       var dateArr = [];
       for(var i = 0;i<res.data.data.lists.rows.length;i++){
         var str = res.data.data.lists.rows[i].signDate.split('-');
          dateArr.push(parseInt(str[2]))
       }
       that.setData({
        punchCardDateArr: dateArr
       })
       that.getAll();
     }else{
        utils.toast(res.data.msg)
     }
  })

    // 注意month范围 0-11，0代表1月
    // const db = wx.cloud.database()
    // db.collection('habitList').where({
    //   _id:this.data.id,
    // }).get().then(res => {
    //   // console.log("从数据库获取数据[res]===", res);
    //   var dateTimeArr = res.data[0].dateTime
    //   var dateArr = []
    //   dateTimeArr.forEach((item) => {
    //     if (item.getFullYear() == year && item.getMonth() == month) {
    //       dateArr.push(item.getDate())
    //     }
    //   })
    //   console.log(year, month,this.data.currentDate);
    //   if (!this.data.currentDate ||(year==this.data.nowYear && month>this.data.nowMonth)||(year==this.data.nowYear && month==this.data.nowMonth &&this.data.currentDate>this.data.nowDate) ) {
    //     // 打卡按钮禁用的情况（1）页面初始化时，未点击任何日期（2）当前点击的日期在今天之后
    //     var flag = true
    //   } else {
    //     // 打卡按钮禁用的情况 （3）当前日期已打卡
    //     var flag = dateArr.indexOf(this.data.currentDate) == -1 ? false : true
    //   }
  
    //   this.setData({
    //     habitInfo: res.data[0],
    //     punchCardDateArr: dateArr,
    //     disabledFlag: flag,
    //     totalDays:dateTimeArr.length,
    //     monthDays:dateArr.length
    //   })
  
    // }).catch(err => {
    //   console.log(err);
    // })
  },
  
  // 点击打卡按钮-打卡
  punchCard() {
    var that = this;
    utils.request('sign/doSign', {
     
  }, function (res) {
     if(res.data.code==200){
        utils.toast('签到成功,本次获得余额奖励'+res.data.data.amount+'元，可直接用于打印',4000)
        that.getHabitInfo(that.data.currentYear, that.data.currentMonth - 1)
     }else{
        utils.toast(res.data.msg)
     }
  })
    // console.log(this.data.currentYear, this.data.currentMonth - 1, this.data.currentDate);
    // var currentTime = new Date(this.data.currentYear, this.data.currentMonth - 1, this.data.currentDate)
    // const db = wx.cloud.database()
    // db.collection('habitList').doc(this.data.id).update({
    //   data: {
    //    dateTime:db.command.push(currentTime)
    //   },
    //   success: res => {
    //     wx.showToast({
    //       title: '打卡成功',
    //     })
    //     this.getHabitInfo(this.data.currentYear, this.data.currentMonth - 1)
    //   },
    //   fail: err => {
    //     wx.showToast({
    //       icon: 'none',
    //       title: '新增记录失败'
    //     })
    //     console.error('[数据库] [新增记录] 失败：', err)
    //   }
    // })
  },
  onShow: function () {
    var nowYear = new Date().getFullYear()
    var nowMonth = new Date().getMonth()
    if (this.data.firstOpen == 1) {
      this.getHabitInfo(nowYear,nowMonth);
    } else {
      this.setData({
        firstOpen: 1
      })
    }
  }
})
